跳到主要内容

ES6 的 Fetch 网络请求工具

Fetch 是什么?

Fetch 是浏览器提供的原生 AJAX 接口(基于 Promise 写的),Fetch API 就是浏览器提供的用来代替 jQuery.ajax 的工具

fetch(url)
.then(fn2)
.then(fn3)
.then(fn4)
...
.catch(fn)

使用例

fetch('http://example.com/movies.json')
.then(function(response) {
// 注意:这里的 json() 还有后面的 text() 都是 fetch 的一部分
// 用于返回数据
return response.json();
})
.then(function(myJson) {
console.log(myJson);
});

其实可以使用协程的写法,如下:

async function test(path: string) {
state.isLoading = true;
try {
// 发出一个网络请求
const response = await fetch(path);

if (!response.ok) {
throw new Error(`Unable to load`);
}

const text = await response.text();
console.log(text);

} catch (e) {
console.log(e);
}
}

注意上面的 text() 方法

如果直接打印 response 出来,很明显是一个 Response

fetch("http://localhost:3000/data")
.then(data => {
console.log(data);
})

返回结果如下:

body: ReadableStream // 注意,这个是后端转成 Stream 发送给前端的数据
locked: false
bodyUsed: false
headers: Headers
ok: true
redirected: false
status: 200
statusText: "OK"
type: "cors"
url: "http://localhost:3000/data"

那打印 text() 的结果会是什么呢?

fetch("http://localhost:3000/data")
.then(data => {
// 这个 text() 只能执行一次?
console.log(data.text());
})

返回结果如下:

Promise {<pending>}
[[PromiseStatus]]: "fulfilled"
[[PromiseValue]]: "Hello World!"

所以可知 只能执行一次的原因是 text() 方法会把 ReadableStream 解析成文本封装到 Promise 对象里面去(所以可以直接在下一个 then 里直接读取到数据),且执行完之后就把这个 ReadableStream 释放掉了,因此 text() 只能执行一次,不过一般都是做返回值 return text()

GET 请求

GET 有两种传递参数的方式

传统的把参数写在URL里面

fetch("http://localhost:3000/data?id=123")
.then(data => {
return data.text()
})
.then(data => {
// 这里才能拿到数据,原因上面讲了
console.log(data);
})

使用 RestFul 风格

fetch("http://localhost:3000/data/123", {method:'GET'})
.then(data => {
return data.text()
})
.then(data => {
// 这里才能拿到数据,原因上面讲了
console.log(data);
})

POST 请求

使用 POST 方法可以搭配 body 属性传递参数 使用encodeURI來做转码

const uri = 'https://script.google.com/macros/s/AKfycbxXH6aPsldTBeS41WRMnJEA5Xstc7cYMj6YimDO2Al7H6DkJZiz/exec';
fetch(uri, {
method:'POST',
body:encodeURI(JSON.stringify({
name:'alsritter',
age:18
})),
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
}
})
.then(res => {
return res.json();
}).then(result => {
console.log(result);
});

fetch响应结果

响应的数据格式

text():将返回体处理成字符串类型 json():返回结果和 JSON.parse(responseText) 一样

在 Express 里返回 Json 格式的数据

app.get('/axios-json', (req, res) => {
res.json({
name: 'alsritter',
age: 12
});
})

接收数据

Reference

参考资料 MDN--使用 Fetch 参考资料 JavaScript.info--Fetch-现代JavaScript 教程 参考资料 alsritter--JavaScript知识拓展01